package me.zhengjie.gas.service;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

@Service
public class ACEService {

	@Value("${tools.aceKey}")
	private String aceKey;

	@Value("${tools.ivKey}")
	private String ivKey;


	// 实现ACE解密
	public String decrypt(String encryptedText) {
		try {
			byte[] encryptedData = Base64.decodeBase64(encryptedText);
			byte[] keyBytes = aceKey.getBytes("UTF-8");
			byte[] ivBytes = ivKey.getBytes("UTF-8");

			SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
			IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

			byte[] decryptedData = cipher.doFinal(encryptedData);
			String decryptedText = new String(decryptedData, "UTF-8");

			return decryptedText;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String encrypt(String text) {
		try {
			byte[] keyBytes = aceKey.getBytes("UTF-8");
			byte[] ivBytes = ivKey.getBytes("UTF-8");

			SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
			IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

			byte[] encryptedData = cipher.doFinal(text.getBytes("UTF-8"));
			String encryptedText = Base64.encodeBase64String(encryptedData);
			return encryptedText;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
